import VueRouter from 'vue-router'

VueRouter.prototype.ln = (path, to)->
    pos = path.indexOf(' ')
    history = @history

    route = @match('/'+path, history.current)
    history.confirmTransition(
        route
        =>
            history.updateRoute(route)
            setTimeout =>
                history.current = @match(
                    to or location.pathname
                    history.current
                )
                history.ensureURL()
    )
    return

VueRouter.prototype.reload = ->
    history = @history
    current = history.current
    GO.go current
    return

module.exports = VueRouter

# `const AsyncFunction = (async ()=>{}).constructor`

# async_data = (mod)->
#     data = mod.data
#     _ = undefined


#     beforeRouteEnter = mod.beforeRouteEnter

#     if beforeRouteEnter
#         mod.beforeRouteEnter = (from, to, next)->
#             _ = await data()
#             beforeRouteEnter.apply(@,arguments)
#     else
#         mod.beforeRouteEnter = (from, to, next)->
#             _ = await data()
#             next()

#     mod.data = ->
#         _



MOD = require '../../.import'
CLS_LOADING = 'I-loading'
_component = (k, patch)->
    =>
        $('body').addClass CLS_LOADING
        mod = (await MOD[k]).default
        # data = mod.data
        # if data instanceof AsyncFunction
        #     async_data(mod)
        if patch
            patch(mod)
        return _loading_patch(mod)

_loading_patch = (mod)->
    body = $ 'body'
    beforeRouteEnter = mod.beforeRouteEnter
    if beforeRouteEnter
        mod.beforeRouteEnter = (to, from, next)->
            beforeRouteEnter(
                to
                from
                ->
                    r = next.apply @,arguments
                    body.removeClass CLS_LOADING
                    return r
            )
    else
        mod.beforeRouteEnter = (to, from, next)->
            next()
            body.removeClass CLS_LOADING
            return
    return mod

_load = (dict, _routes, prefix="")->
    for path,mod of dict.default
        if typeof(mod) == "string"
            _routes.push {
                path:"/"+prefix+path
                component : _component(
                    (prefix or require('~config/site')+"/") + mod
                    dict.patch
                )
            }
        else
            _prefix = prefix+path
            if _prefix.length
                _prefix += "/"

            _load(mod, _routes, _prefix)


window.GO = new VueRouter({
    mode: 'history'
    routes: do ->
        _routes = []
        _load(require('../../route'), _routes)
        # for i in _routes
        #     console.log i
        _routes.push {
            path:"*"
            component: ->
                mod = await `import("../../vue/404.vue")`
                return _loading_patch(mod.default)
        }
        _routes
})
